package com.idsmanager.oauth.infrastructure.mongodb;


import com.idsmanager.commons.utils.mongo.AbstractMongoSupport;
import com.idsmanager.oauth.domain.oauth.OauthClientRepository;
import com.idsmanager.oauth.domain.oauth.AuthorizationCode;
import com.idsmanager.oauth.domain.oauth.OauthClientDetails;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoOperations;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Repository;

import java.util.List;

@Repository("oauthClientRepositoryMongoDB")
public class OauthClientRepositoryMongoDB extends AbstractMongoSupport implements OauthClientRepository {
    @Autowired
    private MongoOperations mongoTemplate;


    @Override
    public OauthClientDetails findOauthClientDetails(String clientId) {
        Query query = createIDQuery(clientId);
        return mongoTemplate.findOne(query, OauthClientDetails.class);
    }

    @Override
    public List<OauthClientDetails> findAllOauthClientDetails() {
        return mongoTemplate.findAll(OauthClientDetails.class);
    }

    @Override
    public void saveOauthClientDetails(OauthClientDetails clientDetails) {
        mongoTemplate.insert(clientDetails);
    }

    @Override
    public boolean removeOauthClientDetails(OauthClientDetails clientDetails) {
        mongoTemplate.remove(clientDetails);
        return true;
    }

    @Override
    public void saveAuthorizationCode(AuthorizationCode authorizationCode) {
        mongoTemplate.save(authorizationCode);
    }

    @Override
    public AuthorizationCode removeAuthorizationCode(String code) {
        final AuthorizationCode authorizationCode = findById(AuthorizationCode.class, code);
        this.mongoTemplate().remove(authorizationCode);
        return authorizationCode;
    }

    @Override
    public String findResourceIdsByClientId(String clientId) {
        final OauthClientDetails oauthClientDetails = findOauthClientDetails(clientId);
        return oauthClientDetails != null ? oauthClientDetails.resourceIds() : null;
    }

}
